﻿using Library.Core.Domain;
using Library.Core.Domain.Specification;
using Synthesize.BaseSet.Domain.Aggregation.Entity.Authority;
using Synthesize.BaseSet.Domain.Repository.Authority;
using System;
using System.Threading.Tasks;

namespace Synthesize.BaseSet.Domain.Specifications.Authority.Department
{
    public class UpdateDepartmentSpecification : IOperateSpecification<DepartmentInfoEntity>
    {
        private readonly IDepartmentRepository _departmentRepository;

        public UpdateDepartmentSpecification(IDepartmentRepository departmentRepository)
        {
            _departmentRepository = departmentRepository;
        }
        public async Task<bool> SatisfiedBy(DepartmentInfoEntity entity)
        {
            if (!await _departmentRepository.AnyAsync(x => x.Id == entity.Id))
            {
                throw new DomainException("无对应部门信息！");
            }
            if (await _departmentRepository.AnyAsync(x => x.Name == entity.Name && !x.Id.Equals(entity.Id) && x.ParentId.Equals(entity.ParentId)))
            {
                throw new DomainException("同一层级内,部门名不能重复");
            }
            if (entity.ParentId.Equals(entity.Id))
            {
                throw new DomainException("不能以自己作为上级部门");
            }
            if (entity.ParentId.HasValue && !await _departmentRepository.AnyAsync(x => x.Id == entity.ParentId))
            {
                throw new DomainException("上级部门不存在");
            }
            return true;
        }
    }
}
